package org.bt.common.validator;

import org.bt.common.validator.aspect.Email;
import org.bt.common.validator.aspect.Pattern;
import org.hibernate.validator.internal.util.logging.Log;
import org.hibernate.validator.internal.util.logging.LoggerFactory;

import javax.validation.ConstraintValidatorContext;
import java.lang.invoke.MethodHandles;
import java.util.regex.Matcher;
import java.util.regex.PatternSyntaxException;

/**
 * EmailValidator
 * <p>
 * Created on 2020/1/9
 *
 * @author tongw
 */
public class EmailValidator extends AbstractEmailValidator<Email> {
    private static final Log LOG = LoggerFactory.make(MethodHandles.lookup());
    private java.util.regex.Pattern pattern;

    public EmailValidator() {
    }

    @Override
    public void initialize(Email emailAnnotation) {
        super.initialize(emailAnnotation);
        Pattern.Flag[] flags = emailAnnotation.flags();
        int intFlag = 0;
        Pattern.Flag[] var4 = flags;
        int var5 = flags.length;

        for (int var6 = 0; var6 < var5; ++var6) {
            Pattern.Flag flag = var4[var6];
            intFlag |= flag.getValue();
        }

        if (!".*".equals(emailAnnotation.regexp()) || emailAnnotation.flags().length > 0) {
            try {
                this.pattern = java.util.regex.Pattern.compile(emailAnnotation.regexp(), intFlag);
            } catch (PatternSyntaxException var8) {
                throw LOG.getInvalidRegularExpressionException(var8);
            }
        }
    }

    @Override
    public boolean isValid(CharSequence value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        } else {
            boolean isValid = super.isValid(value, context);
            if (this.pattern != null && isValid) {
                Matcher m = this.pattern.matcher(value);
                return m.matches();
            } else {
                return isValid;
            }
        }
    }
}
